﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;

namespace SAP
{
    public partial class P_Quotation : System.Web.UI.Page
    {
        private static int GeneralID;
        private static string dbType;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                dbType = Session[VSM.Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? VSM.Utils.AppConstants.VSM : VSM.Utils.AppConstants.DEALER;
                GeneralID = Request.QueryString["GeneralID"] == null ? -1 : Int32.Parse(Request.QueryString["GeneralID"]);
                hf_GeneralID.Value = GeneralID.ToString();
                int RequestType = Request.QueryString["requestType"] == null ? 0 : Int32.Parse(Request.QueryString["requestType"]);

                Services sv = new Services();
                string sql = " select gs.JobID, gs.Receptionist, gs.AdviserCode, gs.TechnicianCode, jk.Name as JobKind, pm.Name as PaymentMethod, ";
                sql += " gs.DateIn, gs.TimeIn, gs.ExpDelivery, gs.ExpTime, gs.StartDate, gs.StartTime, ";
                sql += " gs.VehicleCode, gs.VIN, gs.CustomerCode, ";
                sql += " adv.Name AdviserName, tec.Name TechnicianName, ";
                sql += " gs.FinishDate, gs.FinishTime, gs.ActualDelivery, gs.ActualDeliveryTime, gs.CustomerRequest, gs.Notice, ";
                sql += " gs.Odometer, gs.ServiceDate, gs.JobKind, ";
                sql += " gs.VehicleName, gs.Brand, gs.EngineNo, gs.RegNo, gs.Model, gs.ColorCode, gs.CustomerName, gs.OtherName, ";
                sql += " gs.Address, gs.Tel, gs.TaxCode, gs.ContactPerson, gs.ContactPhone, gs.Mobile, gs.Payment ";
                sql += " from U_GeneralService gs ";
                sql += " left join VSM_ORG..[@JOBKINDSVC] jk on jk.Code = gs.JobKind";
                sql += " left join VSM_ORG..[@PAYMENTMETHODSVC] pm on pm.Code = gs.Payment ";
                sql += " left join VSM_ORG..[@TECHNICIAN] adv on gs.AdviserCode = adv.Code ";
                sql += " left join VSM_ORG..[@TECHNICIAN] tec on gs.TechnicianCode = tec.Code ";
                sql += " where gs.GeneralID = " + GeneralID.ToString();

                DataSet ds = sv.ExecuteQuery(dbType, sql);
                if (ds.Tables[0].Rows.Count > 0) {
                    DataRow dr = ds.Tables[0].Rows[0];

                    txt_VIN.Text = ds.Tables[0].Rows[0]["VIN"].ToString();
                    txt_Brand.Text = ds.Tables[0].Rows[0]["Brand"].ToString();
                    txt_VehicleName.Text = ds.Tables[0].Rows[0]["VehicleName"].ToString();
                    txt_EngineNo.Text = ds.Tables[0].Rows[0]["EngineNo"].ToString();
                    txt_RegNo.Text = ds.Tables[0].Rows[0]["RegNo"].ToString();
                    txt_Model.Text = ds.Tables[0].Rows[0]["Model"].ToString();

                    txt_CusName.Text = ds.Tables[0].Rows[0]["CustomerName"].ToString();
                    txt_OtherName.Text = ds.Tables[0].Rows[0]["OtherName"].ToString();
                    txt_Address.Text = ds.Tables[0].Rows[0]["Address"].ToString();
                    txt_Tel.Text = ds.Tables[0].Rows[0]["Tel"].ToString();
                    txt_Mobile.Text = ds.Tables[0].Rows[0]["Mobile"].ToString();
                    txt_TaxCode.Text = ds.Tables[0].Rows[0]["TaxCode"].ToString();
                    txt_ContactPerson.Text = ds.Tables[0].Rows[0]["ContactPerson"].ToString();
                    txt_PhoneContact.Text = ds.Tables[0].Rows[0]["ContactPhone"].ToString();

                    txt_Odometer.Text = dr["Odometer"].ToString();
                    txtDate.Text = FormatDate(dr["ServiceDate"].ToString());
                    txt_QuotationNo.Text = "QT-" + dr["JobID"].ToString();
                    txt_Notice.Text = dr["Notice"].ToString();
                    DataSet dsPayment = sv.ExecuteQuery(dbType, "select * from [@PAYMENTMETHODSVC] where Code = '" + dr["Payment"].ToString() + "'");
                    if (dsPayment.Tables[0].Rows.Count > 0) {
                        txt_Payment.Text = dsPayment.Tables[0].Rows[0]["Name"].ToString();
                    }
                    loadDetail();
                   
                }

            }
        }

        private void loadDetail()
        {
            Services sv = new Services();
            string sqDetail = "select ROW_NUMBER() over (ORDER BY DetailCode) RowNum, DetailCode, GeneralID, ItemCode, ItemName, FrgnName, Quantity, Price, ";
            sqDetail += " VAT, DiscPrcnt, Stock, cast (isnull(IsSelected, 0) as bit) IsSelected from U_GeneralServiceDetail  where GeneralID = " + GeneralID.ToString();
            Session["dtQuotation"] = sv.ExecuteQuery(dbType, sqDetail).Tables[0];
            grvPO.DataSource = (DataTable)Session["dtQuotation"];
            grvPO.DataBind();
            CalcTotal();
        }
        private string FormatDate(string dateIn)
        {
            if (dateIn.Trim() == "")
                return "";
            DateTime pars = DateTime.Parse(dateIn);
            return pars.ToString("dd/MM/yyyy");

        }

        private void loadVehicleByVIN(string VIN)
        {
            if (VIN == "")
                return;
            Services sv = new Services();

            string sql = "select rn.DistNumber as VIN, rn.Notes as EngineNo, ms.Name as Model, ";
            sql += " cg.RegistrationNumber as RegNo, ";
            sql += " it.ItemName as VehicleName, rn.U_KeyNo as KeyNo, ms.Code as ModelCode, ";
            sql += " it.U_Color as ColorCode, rn.LotNumber as LotNo, it.UserText as Remarks ";
            sql += " from  OSRN rn ";
            sql += " join OITM it on it.ItemCode = rn.ItemCode ";
            sql += " join [@ModelSales] ms on ms.Code = it.U_ModelSales ";
            sql += " left join U_CustomerRegis cg on cg.VIN = rn.DistNumber ";
            sql += " where rn.DistNumber = '" + VIN + "' ";
            DataSet ds = sv.ExecuteQuery("VSM", sql);

            if (ds.Tables[0].Rows.Count > 0)
            {
                txt_VIN.Text = ds.Tables[0].Rows[0]["VIN"].ToString();
                txt_Brand.Text = ds.Tables[0].Rows[0]["Brand"].ToString();
                txt_VehicleName.Text = ds.Tables[0].Rows[0]["VehicleName"].ToString();
                txt_EngineNo.Text = ds.Tables[0].Rows[0]["EngineNo"].ToString();
                txt_RegNo.Text = ds.Tables[0].Rows[0]["RegNo"].ToString();
                txt_KeyNo.Text = ds.Tables[0].Rows[0]["KeyNo"].ToString();
                txt_Model.Text = ds.Tables[0].Rows[0]["Model"].ToString();
            }
        }

        private void loadVehicle(string vehicleID)
        {
            Services sv = new Services();
            DataSet ds = sv.ExecuteQuery(dbType, "select * from U_ServiceVehicle where VehicleID = " + vehicleID);
            if (ds.Tables[0].Rows.Count > 0)
            {
                txt_VIN.Text = ds.Tables[0].Rows[0]["VIN"].ToString();
                txt_Brand.Text = ds.Tables[0].Rows[0]["Brand"].ToString();
                txt_VehicleName.Text = ds.Tables[0].Rows[0]["VehicleName"].ToString();
                txt_EngineNo.Text = ds.Tables[0].Rows[0]["EngineNo"].ToString();
                txt_RegNo.Text = ds.Tables[0].Rows[0]["RegNo"].ToString();
                txt_KeyNo.Text = ds.Tables[0].Rows[0]["KeyNo"].ToString();
                txt_Model.Text = ds.Tables[0].Rows[0]["Model"].ToString();
            }
        }

        private void loadCustomer(string CustomerCode)
        {
            MasterData masterDataWS = new MasterData();
            DataSet ds = masterDataWS.GetCustomerByCode("VSM", CustomerCode);
            if (ds.Tables[0].Rows.Count > 0)
            {
                txt_CusName.Text = ds.Tables[0].Rows[0]["CardName"].ToString();
                txt_OtherName.Text = ds.Tables[0].Rows[0]["CardFName"].ToString();
                txt_Address.Text = ds.Tables[0].Rows[0]["Address"].ToString();
                txt_Tel.Text = ds.Tables[0].Rows[0]["Phone1"].ToString();
                txt_TaxCode.Text = ds.Tables[0].Rows[0]["LicTradNum"].ToString();
                txt_ContactPerson.Text = ds.Tables[0].Rows[0]["U_ContactPerson"].ToString();
                txt_PhoneContact.Text = ds.Tables[0].Rows[0]["U_ContactPhone"].ToString();
                txt_Mobile.Text = ds.Tables[0].Rows[0]["Cellular"].ToString();
            }
        }

        protected void btn_Save_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.grvPO.Rows.Count; i++)
            {
                CheckBox checkBox = (CheckBox)this.grvPO.Rows[i].FindControl("chk_Selected");

                if (checkBox != null)
                {

                    Label gID = (Label)this.grvPO.Rows[i].FindControl("lbDetailCode");
                    string sql = "UPDATE U_GeneralServiceDetail SET IsSelected = " + (checkBox.Checked == true ? "1" : "0") + " WHERE DetailCode = " + gID.Text;
                    Services sv = new Services();
                    sv.ExecuteQuery("DEALER", sql);
                }
            }
            ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Update Complete');", true);
            loadDetail();
            CalcTotal();
        }

        private void CalcTotal()
        {
            try
            {

                DataTable dtTmp = (DataTable)Session["dtQuotation"];

                double subTotal = 0;
                double vatAmount = 0;
                double discountAmount = 0;
                double grandTotal = 0;
                foreach (DataRow row in dtTmp.Rows)
                {
                    if (Boolean.Parse(row["IsSelected"].ToString()) == true)
                    {
                        double qty = Double.Parse(row["Quantity"].ToString());
                        double price = Double.Parse(row["Price"].ToString());
                        double lineTotal = qty * price;
                        subTotal += lineTotal;

                        if (row["VAT"] != null && row["VAT"].ToString().Length > 0)
                        {
                            double vatPercent = double.Parse(row["VAT"].ToString());
                            vatAmount += (vatPercent / 100) * lineTotal;
                        }
                        if (row["DiscPrcnt"] != null && row["DiscPrcnt"].ToString().Length > 0)
                        {
                            double discountLine = double.Parse(row["DiscPrcnt"].ToString());
                            discountAmount += (discountLine / 100) * lineTotal;
                        }
                    }
                }
                grandTotal = subTotal + vatAmount - discountAmount;
                lb_SubTotal.Text = string.Format("{0:C}", Math.Round(subTotal, 2));
                lb_VATAmount.Text = string.Format("{0:C}", Math.Round(vatAmount, 2));
                lb_DiscountAmt.Text = string.Format("{0:C}", Math.Round(discountAmount, 2));
                lb_GrandTotal.Text = string.Format("{0:C}", Math.Round(grandTotal, 2));

            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }

    }
}